﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace ArchiveLinkService
{
    using System.ComponentModel;
    using System.IO;
    using ArchiveLink;

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class LinkerService : ILinker
    {
        private Linker Linker { get; set; }
        private ILinkerCallback _callback;
        private ILinkerCallback Callback
        {
            get
            {
                if (_callback==null && OperationContext.Current != null)
                {
                    _callback= OperationContext.Current.GetCallbackChannel<ILinkerCallback>();
                }
                return _callback;
            }
        }

        //private string _test;

        //private BackgroundWorker w;

        //public void Set(string source)
        //{
        //    _test = source;
        //}

        //public string Get()
        //{
        //    w= new BackgroundWorker();
        //    w.DoWork += new DoWorkEventHandler(w_DoWork);
        //    var callback = OperationContext.Current.GetCallbackChannel<ILinkerCallback>();
        //    w.RunWorkerAsync(callback);
            
            

        //    return _test;
        //}

        //void w_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    System.Threading.Thread.Sleep(1000);

        //    var callback= (ILinkerCallback) e.Argument;

        //    var s = callback.Getc();
        //}

        public LinkerService(EventLog eventLog)
        {
            Linker = new Linker(eventLog);
            Linker.DriveArrived += new ArchiveLink.Linker.DriveArrivedHandler(Linker_DriveArrived);
            Linker.StartDriveWatcher();
        }

        void Linker_DriveArrived(object sender, Linker.DriveEventArgs e)
        {
            if (Callback != null)
            {
                e.Cancel = !Callback.DriveChanged(e.Name, e.Drive, e.IsMirrored);
            }
        }
        
        public void Connect()
        {
            _callback = null;
            if (Callback != null)
            {

            }
            //Linker.StartDriveWatcher();
        }

        public void AddDrive(string drive)
        {
            Linker.AddNewDrive(new DriveInfo(drive));
        }

        public void Configure(Configuration config)
        {
            Linker.Configure(config);
        }

        public Configuration GetConfig()
        {
            return Linker.GetConfig();
        }
    }
}
